<template>
  <div class="login-page">
    <div class="login-container">
      <div class="logo">
        <img src="@/assets/logo.png" alt="Logo">
      </div>

      <div class="form-container">
        <div class="form-item">
          <div class="form-label">手机号</div>
          <div class="form-input">
            <van-field v-model="phoneNumber" placeholder="请输入手机号" :rules="[{ required: true, message: '请填写手机号' }]"
              type="tel" maxlength="11" />
          </div>
        </div>

        <div class="form-item">
          <div class="form-label">验证码</div>
          <div class="form-input code-input">
            <van-field v-model="verifyCode" placeholder="请输入验证码" :rules="[{ required: true, message: '请填写验证码' }]"
              type="digit" maxlength="6" />
            <van-button size="small" type="primary" class="code-btn" :disabled="cooldown > 0" @click="getCode">
              {{ cooldown > 0 ? `${cooldown}s后重新获取` : '获取验证码' }}
            </van-button>
          </div>
        </div>

        <div class="login-btn">
          <van-button block type="primary" :loading="loading" @click="handleLogin">
            登录
          </van-button>
        </div>

        <div class="agreement" @click="openAgreement">
          登录即代表您同意<span class="agreement-link">《用户协议》</span>和<span class="agreement-link">《隐私政策》</span>
        </div>
      </div>

    </div>

  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast, showSuccessToast, showFailToast, showDialog } from 'vant';
import { getVerifyCode, login } from '@/api/user';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 表单数据
const phoneNumber = ref('');
const verifyCode = ref('');
const loading = ref(false);
const cooldown = ref(0);
let timer = null;

// 获取验证码
const getCode = async () => {
  if (cooldown.value > 0) return;

  // 验证手机号
  if (!phoneNumber.value || phoneNumber.value.length !== 11) {
    showToast('请输入正确的手机号');
    return;
  }
  openAgreement();
  try {
    const response = await getVerifyCode(phoneNumber.value);
    if (response.code === "10000" && response.data === true) {
      showSuccessToast('验证码已发送');

      // 开始倒计时
      cooldown.value = 60;
      timer = setInterval(() => {
        cooldown.value--;
        if (cooldown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      showFailToast(response.message || '验证码发送失败');
      console.error('验证码发送失败:', response);
    }
  } catch (error) {
    console.error('验证码请求错误:', error);
    showFailToast(error.response?.data?.message || error.message || '验证码发送失败，请检查网络');
  }
};

// 处理登录
const handleLogin = async () => {
  // 验证表单
  if (!phoneNumber.value || phoneNumber.value.length !== 11) {
    showToast('请输入正确的手机号');
    return;
  }

  if (!verifyCode.value || verifyCode.value.length !== 6) {
    showToast('请输入6位验证码');
    return;
  }

  loading.value = true;

  try {
    const response = await login({
      phone: phoneNumber.value,
      code: verifyCode.value
    });

    if (response.code === "10000") {
      // 从响应中获取token
      const token = response.data.tokenInfo?.access_token || 'mock-token';

      // 保存登录状态
      userStore.setLogin({
        phone: phoneNumber.value,
        token: token,
        userData: response.data
      });

      showSuccessToast('登录成功');

      // 跳转到目标页面或首页
      const redirectPath = route.query.redirect || '/';
      router.replace(redirectPath);
    } else {
      console.error('登录失败:', response);
      showFailToast(response.message || '登录失败');
    }
  } catch (error) {
    console.error('登录请求错误:', error);
    showFailToast(error.response?.data?.message || error.message || '登录失败，请检查网络');
  } finally {
    loading.value = false;
  }
};

// 组件销毁时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
});
const isOpen = ref(false)

const openAgreement = (isShow) => {
  if (!isShow && isOpen.value) {
    return;
  }
  showDialog({
    message: `<div class="disclaimer"><strong>非官方声明：</strong>本平台为第三方独立运营网站，未获得任何赞助。\n<strong>隐私保护声明：</strong>本站不会主动收集、存储或泄露您的个人信息。登录所使用的手机号与验证码仅用于临时身份验证，不会用于其他用途，也不会共享给任何第三方。
<strong>免责声明：</strong>本站内容来源于信息整理，仅供技术交流与参考使用。因使用本站信息导致的任何损失或风险，均由用户自行承担，本站不承担法律责任。<p class="contact">如有侵权或合作事宜，请联系邮箱：
<a href="mailto:qianxumanniu@163.com" class="email-link">qianxumanniu@163.com</a></p><div>`,
    allowHtml: true,
  }).then(() => {
    isOpen.value = true;
  });
};
</script>

<style lang="scss" scoped>
.login-page {
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;

  .login-container {
    max-width: 400px;
    background-color: #fff;
    border-radius: 12px;
    padding: 30px 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  }

  .logo {
    text-align: center;

    img {
      border-radius: 50%;
      border: 1px solid #eee;
      height: 75px;
      width: 77px;
    }

    h1 {
      font-size: 22px;
      color: #333;
      margin-top: 10px;
      font-weight: 500;
    }
  }

  .form-container {
    .form-item {
      margin-bottom: 20px;
    }

    .form-label {
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
    }

    .form-input {
      position: relative;

      &.code-input {
        display: flex;
        align-items: center;

        :deep(.van-field) {
          flex: 1;
        }

        .code-btn {
          margin-left: 10px;
          width: 110px;
          border-radius: 4px;
        }
      }
    }

    .login-btn {
      margin-top: 30px;

      :deep(.van-button) {
        height: 44px;
        font-size: 16px;
        border-radius: 4px;
      }
    }

    .agreement {
      margin-top: 15px;
      font-size: 12px;
      color: #999;
      text-align: center;

      .agreement-link {
        color: #1989fa;
      }
    }
  }
}

.disclaimer {
  font-size: 12px;
  color: #666;
  line-height: 1.6;
  text-align: left;
  padding: 0px 5px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #eaeaea;

  p {
    margin: 0;
  }

  .contact {
    margin-top: 5px;
    font-style: italic;
  }

  .email-link {
    color: #1989fa;
    text-decoration: underline;
  }
}

:deep(.van-field) {
  border-bottom: 1px solid #eaeaea;
}
</style>